// pages/home/main/index.js
const app = getApp()
const utils = require('./../../../utils/util.js')
Page({
/**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight,
    swipList: [], // 首页banner轮播图
    // statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
    // screenHeight: wx.getSystemInfoSync().screenHeight,
    isIphoneX: app.globalData.isIphoneX,
    templateList: [],
    recommendList: [],
    tipsPopShow:false,
    toCrmParams:'',
    headerBgSrc:'',
    navHeaderSrc:'',
    topWholeVideoImageUrl:"",//整家视频图片
    bottom:60,
    right:58,
    hourseStyles:[],
    Allhouse:{
      title:'全屋方案',
      Introduction:'盘点最备受瞩目的全屋设计案例',
      id:0
    },
    lifestyle:{
      title:'家·生活方式',
      Introduction:'打造您的专属梦想家',
      id:1
    },
    lifeData:[],
    Newproduct:{
      title:'新品品鉴',
      Introduction:'潮流新品,一应俱全',
      id:2
    },
    NewproData:[],
    SpaceFeatured:{
      title:'家·空间',
      Introduction:'细致打造友品生活',
      id:3
    },
    homeSpaceList:[], // 家空间 列表
    recommend:{
      title:'最in推荐',
      Introduction:'您所关注的都在这里，每日为您精选最in居住案例',
      id:4
    },
    recommendData:[],
    hasNoDatas: false,
    page:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const openId =  wx.getStorageSync('openId') || ''
    if(openId && openId.length > 0){
      this.gotoGuidePage(wx.getStorageSync('openId'))
      this.getHomeData()
    } else {
      app.globalData.openIdHandler = () => {
        this.gotoGuidePage(wx.getStorageSync('openId'))
        this.getHomeData()
      }
    }
   
    this.setData({
      toCrmParams: JSON.stringify({ url: '/pages/home/main/index'})
    })

    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.setupInit()
    // this.getTopTipsRect()
  },
  // header banner 跳转
  bannerImageJump(e){
    const { url , id, type } = e.currentTarget.dataset
    const params = {id: id}

    if(type === 'PICTURE' || type === 'VIDEO') {
      const newType = type === 'VIDEO' ? 'video' : 'image'
      wx.navigateTo({
        url: `/pages/picShow/index?url=${encodeURIComponent(url)}&type=${newType}`,
        success: () => {
          utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
            // 阅览量
          })
        }
      })
    } else {
      if(url === '/pages/home/main/index' || 
        url === '/pages/Featured/main/index' || 
        url==="/pages/afflatus/main/index" || 
        url === '/pages/mine/main/index' || 
        url === '/pages/design/main/index'
      ) {
        wx.switchTab({
          url: url,
          success: () => {
            utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
              // 阅览量
            })
          }
        })
      } else {
        // 非tab页
        const newURl = url.split('?')[0] ? url.split('?')[0] : url
        if(newURl === '/pages/H5/main/index') {
        const kujialeURl = url.split('?url=')[1] ? url.split('?url=')[1] : ''
          wx.navigateTo({
            url: `/pages/H5/main/index?url=${encodeURIComponent(kujialeURl)}`,
            success: () => {
              utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
                // 阅览量
              })
            }
          })
        }
        else {
          wx.navigateTo({
            url: url,
            success: () => {
              utils.$http(app.globalData.api.SetHomeBannerView, params, 'GET', true, 'JSON').then(res => {
                // 阅览量
              })
            }
          })
        }
      }
    }
  },
  //
  getTopTipsRect(){
    let data = wx.getMenuButtonBoundingClientRect()
    const screenWidth = wx.getSystemInfoSync().screenWidth
    const {bottom,left,width,right} = data
    this.setData({
      bottom:bottom
    })
  },
  //初始化数据
  getHomeData() {
    //获取首页整家视频入口图片
    utils.$http(app.globalData.api.getRealNetworkStaticResources, {}, 'GET', false, 'JSON').then(res => {
      if(res.success){
        this.setData({
          topWholeVideoImageUrl:res.data.filter(item=>item.pageName==="WHOLE_FAMILY_VIDEO")[0].bannerImg
        })
      }
    })
    //获取Banner
    utils.$http(app.globalData.api.GetHomeBanner, {}, 'GET', true, 'JSON').then(res => {
      if(res.data){
        this.setData({
          swipList: res.data,
          navHeaderSrc: res.data[0].smallProgramBackgroundOne,
          headerBgSrc: res.data[0].smallProgramBackgroundTwo,
        })
      }
    })
     //获取全屋风格
     utils.$http(app.globalData.api.GetHomeStyleList,{},'GET',true,'JSON').then(res=>{
      if(res.success === 1){
        const { data = [] } = res
        const dataFilter =  data.filter(item => item.code !== 'CPFG0008' )
        
        this.setData({
          hourseStyles: dataFilter
        })
      }
    }),
    //获取你的专属生活方式
    utils.$http(app.globalData.api.GetHomeSpecialTopicList,{},'GET',true,'JSON').then(res=>{
      if(res.data){
        let data = JSON.parse(JSON.stringify(res.data))
        this.setData({
          lifeData: data
        })
      }
    })
    //获取新品品鉴
    utils.$http(app.globalData.api.GetHomeSeriesList,{},'GET',true,'JSON').then(res=>{
      if(res.data){
        this.setData({
          NewproData: res.data
        })
      }
    })
    // 家 空间
    utils.$http(app.globalData.api.getHomeSpace,{},'GET',true,'JSON').then(res=>{
      if(res){
        this.setData({
          homeSpaceList: res
        })
      }
    })
    //获取最in推荐
    this.remocom(1)
  },
  //最in推荐
  remocom(page,flag){
    let openId = wx.getStorageSync('openId')
    if(!flag){
      this.setData({
        recommendData: []
      })
    }
    utils.$http(app.globalData.api.GetHomeInterestProgramme,{
      openId:openId,
      page:page,
      rows:4,
    },'POST',false,'JSON').then(res=>{
      if(res.success === 1) {
        let datas = this.data.recommendData
        datas.push(...res.data.records)
        this.setData({
          recommendData:datas
        })

        if(res.data.records.length === 0) {
          this.setData({
            hasNoDatas: true
          })
        }

        
      }
    })
  },
  // 是否跳转引导页
  gotoGuidePage(openId){
    utils.$http(app.globalData.api.GetInterestInfo + openId,{},'GET',true,'JSON').then(res=>{
      if(res.success === 1 && res.data){
        const { familyId = '', specialId = '', styleId = ''} = res.data
        if(familyId == '' && specialId =='' && styleId == '') {
          wx.navigateTo({
            url: '/pages/guidePage/index',
          })
        } else {
          return false 
        }
      } else {
        wx.navigateTo({
          url: '/pages/guidePage/index',
        })
      }
    })
  },
  goWholeVodeo(){
    wx.navigateTo({
      url: '/pages/real/wholevideo/index',
    })
  },
  // 全屋方案跳转
  gotoAllHouses(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../homePage/AllHouses/index?id=${id}`,
    })
  },
  setupInit:function(){
    utils.getFrameById('#navigationBar', (frame) => {
      // console.log('frame:', frame)
      if (frame && frame.height) {
        this.setData({
          navHeight: frame.height
        })
        // console.log('frame:', frame)
      }
    })
  },

  searchFocus:function(e){
    wx.navigateTo({
      url: '/pages/Search/main/index',
    })
  },

  bannerChange(e){
    const index = e.detail.current
    this.setData({
      navHeaderSrc: this.data.swipList[index].smallProgramBackgroundOne,
      headerBgSrc: this.data.swipList[index].smallProgramBackgroundTwo,
    })
  },

  ballTap(e){
    console.log('e:',e)
  },

  onClickHide:function(){
     this.setData({
       tipsPopShow:false
     })
  },

  // 点击推荐
  lookMore:function(){
    wx.navigateTo({
      url: '/pages/afflatus/subMain/index',
    })

  },

  bindScroll:function(e){
    console.log('scroll:',e)
  },

  // 风格点击跳转详情
  footerItemClick(e) {
    const idCode = e.currentTarget.dataset.id
    const objType = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/index/index?type=' + objType + '&id=' + idCode,
    })
  },
  
  // 风格 点击
  styleTap:function(e){
    const styleCode = e.currentTarget.dataset.stylecode
    wx.navigateTo({
      url: '../styles/index?stylecode=' + styleCode,
    })
  },
  gotoSelectCase(){
     wx.switchTab({
       url: '/pages/afflatus/main/index',
     })
     app.isSelectCase = true
  },

  onTabItemTap(item) {
    console.log('tabBarItem:', item)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
    // this.showTipsPage()
  },

  showTipsPage:function(){
    const showGuide = wx.getStorageSync("showGuide")
    if (showGuide === false) {
      const isTips = wx.getStorageSync('isTips') || false
      if (!isTips) {
        this.setData({
          tipsPopShow: true
        })
        setTimeout(() => {
          this.setData({
            tipsPopShow: false
          })
        }, 5000)
        wx.setStorageSync('isTips', true)
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
     this.getHomeData()
    //  setTimeout(()=>{
       wx.stopPullDownRefresh()
    //  },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
     this.setData({
       page:this.data.page + 1
     })
     this.remocom(this.data.page,true)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})